#include "RS485.h"
#include "mcc.h"

uint8_t rec_buff[8]={0};   //接收的数据
uint8_t S_Flag=0;          //485发送标志位

/*发送字符串*/
void Send_String(uint8_t *ch)
{
    while(*ch !='\0')
    {
        EUSART_Write(*ch);
        ch++;
    }
}

/*和校验*/
uint8_t GetCheckSum(uint8_t* packet,uint8_t size)
{
	uint8_t i, checksum;
	for( i = 1; i < (size-1); i++)
	{
        checksum += packet[i];
	}
	checksum = (0xff-checksum) +1;
	return checksum;
}


/*发送的数据格式*/
void send_data()
{
    /*编程空间不够存下更多变量，没有调用数组存取发送的值*/
    AS5045.Check_sum=(0xff -(0xb0 +AS5045.Ang_L+AS5045.Ang_H+AS5045.OCF+AS5045.COF+AS5045.LIN+AS5045.Magnetic_Field))+1;
    EUSART_Write(0xa1);              //发送开始 
    EUSART_Write(0xb0);              //设备地址
    EUSART_Write(AS5045.Ang_L);   //角度数据低8位
    EUSART_Write(AS5045.Ang_H);
    EUSART_Write(AS5045.OCF);
    EUSART_Write(AS5045.COF);
    EUSART_Write(AS5045.LIN);   
    EUSART_Write(AS5045.Magnetic_Field);
    EUSART_Write(AS5045.Check_sum);
}

void rec485()
{
    uint8_t i = 0;
    uint8_t check_sum = 0;
    UART_EN_SetLow();
    DELAY_microseconds(3);
    rec_buff[0]=EUSART_Read();
    if(rec_buff[0]==0xa1)           //判断帧头
    {
        for(i=1;i<8;i++)
            rec_buff[i]=EUSART_Read();
        if(rec_buff[1]==0xb0)        //确定设备地址
        {
            check_sum=GetCheckSum(rec_buff,8);
            check_sum=(0xff - (rec_buff[1]+rec_buff[2]+rec_buff[3]+rec_buff[4]+rec_buff[5]+rec_buff[6]))+1;
            if(check_sum==rec_buff[7])     //和校验
            {
                if(rec_buff[2]==0x01)     //读一次发一次
                    S_Flag=1;
                else if(rec_buff[2]==0x02)  //一直读取发送
                    S_Flag=2;
                else if(rec_buff[2]==0x03)  //设置零点
                    S_Flag=3;
                else if(rec_buff[2]==0x00)
                    S_Flag=0;              //不发
                rec_buff[0]=0;
            }
        }
    }
    else
        rec_buff[0]=0;
}

void Send485()
{
    UART_EN_SetHigh();
    DELAY_milliseconds(4);
    send_data();
    DELAY_milliseconds(1);
    UART_EN_SetLow();
    DELAY_microseconds(2);
}
